package com.fresh.bus.chat.ctrl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;

import com.eeplat.social.openapi.http.AuthUtil;
import com.eeplat.social.openapi.http.URIUtil;
import com.eeplat.social.openapi.qq.URIUtilQQ;
import com.eeplat.social.openapi.renren.AuthRenRen;
import com.eeplat.social.openapi.sina.AuthSina;
import com.eeplat.social.openapi.t360.Auth360;
import com.fresh.bus.canoe.command.CallbackEvent;
import com.fresh.bus.canoe.command.annotation.CanoeCallback;
import com.fresh.bus.canoe.command.annotation.CanoeCallbacks;
import com.fresh.bus.canoe.command.annotation.CanoeCommand;
import com.fresh.bus.canoe.message.Request;
import com.fresh.bus.canoe.message.Response;
import com.fresh.bus.canoe.session.Session;

@Controller("loginCtrl")
public class LoginCtrl extends BaseCtrl {

	@CanoeCommand(value = OpCodes.REGISTER, roleRequired = false)
	public Response register(Session session, Request request) {
		@SuppressWarnings("unchecked")
		Map<String, Object> data = (Map<String, Object>) request.getData();
		Response response = new Response(OpCodes.REGISTER);
		try {
			loginService.addUser(data);
			data.put("pass", false);
			response.setData(data);
			return response;
		} catch (DuplicateKeyException e) {
			response.setData("该邮箱已被注册");
			return response;
		} catch (Exception e) {
			log.error("Register failed...", e);
			response.setData("注册失败，请稍候重试。");
			return response;
		}
	}

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.REGISTER_THIRD_PART, roleRequired = false)
	public Response registerThirdPart(Session session, Request request) {
		Map<String, Object> data = (Map<String, Object>) request.getData();
		String action = (String) data.get("action");
		String login = (String) data.get("id");
		String pwd = (String) data.get("password");
		Response response = new Response(OpCodes.REGISTER_THIRD_PART);
		try {
			if (action.equals("new")) {
				loginService.addUser(data);
				response.setData(data);
				return response;
			} else {
				if (loginService.auth(login, pwd)) {
					loginService.updateUserAccount(data);
					data.put("pass", true);
					response.setData(data);
				} else {
					response.setData("登录失败，帐号和密码不匹配。");
				}
				return response;
			}

		} catch (DuplicateKeyException e) {
			response.setData("该邮箱已被注册");
			return response;
		} catch (Exception e) {
			log.error("Register failed...", e);
			response.setData("注册失败，请稍候重试。");
			return response;
		}
	}

	@CanoeCommand(value = OpCodes.INIT_DATA, roleRequired = false)
	public Response initData(Session session, Request request) {
		@SuppressWarnings("unchecked")
		Map<String, Object> data = (Map<String, Object>) request.getData();
		Response response = new Response(OpCodes.INIT_DATA);
		try {
			data.remove("pass");
			loginService.initUserData(session, data);
			response.setData(data);
		} catch (Exception e) {
			log.error("Register failed...", e);
			response.setData("注册失败，请稍候重试。");
			return response;
		}
		return response;

	}

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.LOGIN, roleRequired = false)
	public Response login(Session session, Request request) {
		Map<String, Object> data = (Map<String, Object>) request.getData();
		String login = (String) data.get("id");
		String pwd = (String) data.get("pass");
		// session.setRole(new User(id));
		Response response = new Response(OpCodes.LOGIN);
		try {
			if (loginService.auth(login, pwd)) {
				// String id = userManager.findUid(login);
				// Response response = new Response(InternalOpCodes.SUCCESS);
				data.put("pass", true);
				data.put("isapp",false);
				response.setData(data);
			} else {
				response.setData("登录失败，帐号和密码不匹配。");
			}
			return response;
		} catch (Exception e) {
			log.error("Login failed...", e);
			response.setData("登录失败，请稍候重试。");
			return response;
		}
	}

	@CanoeCommand(value = OpCodes.ENTRY, roleRequired = false)
	public Response entry(Session session, Request request) {
		Map<String, String> data = (Map<String, String>) request.getData();
		String login = data.get("id");
		// session.setRole(new User(id));
		Response response = new Response(OpCodes.ENTRY);
		Map<String, String> user;
		try {
			loginService.setSession(login, session);
			String id = loginService.findUid(login);
			user = userService.findUser(id);
			user.put("isapp", String.valueOf(data.get("isapp")));
			user.put("src", String.valueOf(data.get("src")));
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("user", user);
			map.put("cond", this.friendService.getFriendCond(id));
			response.setData(map);
			return response;
		} catch (Exception e) {
			log.error("Entry failed...", e);
			return null;
		}
		// String id = userManager.findUid(login);
		// Response response = new Response(InternalOpCodes.SUCCESS);
	}

	@CanoeCommand(value = OpCodes.SEND_LOGIN_EXP)
	public Response queryLoginExp(Session session, Request request) {
		// sessionMap.put(id, session);
		Object isFirst = session.getAttribute("isFirst");
		try {
			expService.update(session, null, OpCodes.LOGIN);
		} catch (Exception e) {
			log.error("Cannot retrive login exp...", e);
		}
		// String id = userManager.findUid(login);
		// Response response = new Response(InternalOpCodes.SUCCESS);
		return null;
	}

	@CanoeCallbacks({ @CanoeCallback(CallbackEvent.ONEXITED) })
	public Response logOff(Session session) {
		try {
			loginService.offSession(session);
		} catch (Exception e) {
			log.error("Logoff failed...", e);
		}
		return null;
	}
	

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.LOGIN_RENREN, roleRequired = false)
	public Response loginRenRen(Session session, Request request) {
		Map<String, Object> data = (Map<String, Object>) request.getData();
		Response response = new Response(OpCodes.LOGIN_RENREN);
		try {
			String username;
			Object uid = data.get("uid");
			if(uid != null && !uid.equals("")){
				username = (String)data.get("uid");
			}else{
				String code = (String) data.get("code");
				AuthRenRen u = new AuthRenRen();
				String token = u.getAccessToken(code);
				username = u.getUserID(token);
			}
			data.remove("code");
			// username = "renren-" + username;
			data.put("account", username);
			// data.put("token", token);
			String loginId = this.loginService.authRenRen(username);
			if (loginId != null) {
				data.put("id", loginId);
				data.put("pass", true);
			} else {
				data.put("id", username+"@renren.com");
				data.put("renren_id", username);
				data.put("password", "123456");
				data.put("pass", false);
			}
			response.setData(data);
		} catch (Exception e) {
			log.error("login failed...", e);
		}

		if (response.getData() == null) {
			response.setData("与人人网链接失败，请稍候重试。");
		}
		return response;
	}	

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.LOGIN_360, roleRequired = false)
	public Response login360(Session session, Request request) {
		Response response = new Response(OpCodes.LOGIN_360);
		Map<String, Object> data = (Map<String, Object>) request.getData();
		try {
			String username = (String)data.get("uid");
			if(username.trim().length()>0){
				username = username.trim();
			}else{
				String code = (String) data.get("code");
				Auth360 u = new Auth360();
				String token = u.getAccessToken(code);
				username = u.getUserID(token);
				data.remove("code");
			}
			data.put("account", username);
			// data.put("token", token);
			String loginId = this.loginService.auth360(username);
			if (loginId != null) {
				data.put("id", loginId);
				data.put("pass", true);
			} else {
				data.put("id", username+"@360.cn");
				data.put("360_id", username);
				data.put("password", "123456");				
				data.put("pass", false);
			}
			response.setData(data);
		} catch (Exception e) {
			log.error("login failed..."+ data.get("uid"),e);
		}
		if (response.getData() == null) {
			response.setData("与360链接失败，请稍候重试...");
		}
		return response;
	}

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.LOGIN_QQ, roleRequired = false)
	public Response loginQQ(Session session, Request request) {
		Map<String, Object> data = (Map<String, Object>) request.getData();
		Response response = new Response(OpCodes.LOGIN_QQ);
		try {
			String username = (String)data.get("uid");
			log.info("qq username is:" + username+";pf is:" + data.get("pf"));
			if(username.trim().length()>0){
				username = username.trim();
			}else{
				String code = (String) data.get("code");
				URIUtil uri = new URIUtilQQ();
				AuthUtil qq = new AuthUtil(uri);
				Map<String, Object> user = qq.getUserInfo(code);
				username = (String) user.get("id");
				data.remove("code");
			}
			data.put("account", username);
			// data.put("token", token);
			String loginId = this.loginService.authQQ(username);
			if (loginId != null) {
				data.put("id", loginId);
				data.put("pass", true);
			} else {
				data.put("id", username);
				data.put("qq_id", username);
				data.put("password", "123456");				
				data.put("pass", false);
			}
			response.setData(data);			

		} catch (Exception e) {
			log.error("loginQq failed...", e);
		}

		if (response.getData() == null) {
			response.setData("与QQ链接失败，请稍候重试。");
		}
		return response;
	}

	@SuppressWarnings("unchecked")
	@CanoeCommand(value = OpCodes.LOGIN_SINA, roleRequired = false)
	public Response loginSina(Session session, Request request) {
		Map<String, String> data = (Map<String, String>) request.getData();
		Response response = new Response(OpCodes.LOGIN_SINA);
		String code = data.get("code");
		try {
			AuthSina u = new AuthSina();
			String token = u.getAccessToken(code);
			String username = u.getUserID(token);
			username = "sina-" + username;
			data.put("id", username);
			data.put("pass", "sina");

			Boolean isAuth = this.loginService.auth(username, "sina");
			if (!isAuth) {
				// userManager.addUser(data);
			}
			response.setData(data);
		} catch (Exception e) {
			log.error("loginQq failed...", e);
		}

		if (response.getData() == null) {
			response.setData("与新浪链接失败，请稍候重试。");
		}
		return response;
	}

}
